package cn.edu.ccibe.exam16system.handler;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

public class AuthInterpret implements HandlerInterceptor {

    private final List<String> passUrls = List.of("/", "/login", "/register", "/doLogin", "/doRegister", "/doLogout", "/dormitory");

    private boolean checkPass(String url) {
        return passUrls.contains(url);
    }

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) throws Exception {
        boolean shouldPass = checkPass(request.getRequestURI());
        System.out.println(request.getRequestURI());
        if (shouldPass) return HandlerInterceptor.super.preHandle(request, response, handler);
        HttpSession session = request.getSession();
        Object loginUser = session.getAttribute("loginUsername");
        Object isAdmin = session.getAttribute("isAdmin");
        if (loginUser == null || isAdmin == null) {
            response.sendRedirect("/");
            return HandlerInterceptor.super.preHandle(request, response, handler);
        }
        if (isAdmin instanceof Boolean && (Boolean) isAdmin) {
            return HandlerInterceptor.super.preHandle(request, response, handler);
        }
        return false;
    }

    @Override
    public void postHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
